package com.xiezc;


import java.math.BigDecimal;

/**
 * Created by wb-xzc291800 on 2017/6/29.
 */


public class Solution {
    static Solution solution = new Solution();

    public static void main(String[] args) {

        String x = "719";
        x.substring(0, 1);

        ListNode a = new ListNode(7);
        ListNode a1 = a;
        a.next = new ListNode(1);
        a = a.next;
        a.next = new ListNode(2);

        ListNode b = new ListNode(2);
        ListNode b1 = b;
        b.next = new ListNode(9);
        b = b.next;
        b.next = new ListNode(5);
        b = b.next;
        b.next = new ListNode(1);
        b = b.next;
        solution.addLists2(a1, b1);

    }


    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the sum list of l1 and l2
     */
    public ListNode addLists2(ListNode l1, ListNode l2) {
        String a = getString(l1);
        String b = getString(l2);

        int lenb = b.length();
        int lena = a.length();
        int len = lenb > lena ? lenb : lena;

        int abit = 0;
        int bbit = 0;

        ListNode now;
        ListNode pre = new ListNode(0);
        ListNode ret = pre;

        for (int i = 0; i < len; i++) {
            if (lena < len) {
                if (i + lena >= len) {
                    abit = Integer.parseInt(a.substring(i - len + lena, i - len + lena + 1));
                }
            } else {
                abit = Integer.parseInt(a.substring(i, i + 1));
            }

            if (lenb < len) {
                if (i + lenb >= len) {
                    bbit = Integer.parseInt(b.substring(i - len + lena, i - len + lena + 1));
                }
            } else {
                bbit = Integer.parseInt(b.substring(i, i + 1));
            }


            if (abit + bbit >= 10) {
                pre.val = pre.val + 1;
                now = new ListNode(abit + bbit - 10);
                pre.next = now;
                pre = now;
            } else {
                now = new ListNode(abit + bbit);
                pre.next = now;
                pre = now;
            }
        }

        while (ret.val == 0 && ret.next != null) {
            ret = ret.next;
        }

        return ret;

    }

    private String getString(ListNode l1) {
        String a = "";
        if (l1.next == null) {
            a = a + l1.val + "";
        } else {
            while (true) {
                a = a + l1.val + "";
                l1 = l1.next;
                if (l1.next == null) {
                    a = a + l1.val + "";
                    break;
                }
            }
        }
        return a;
    }


}

